#!/usr/bin/env python3
# -*- coding:utf-8 -*-
## author : mike
## date   : 2014.12.9
"""
"""
import os 
import sys
from os.path import realpath, dirname, basename, isdir

sys.path.append(dirname(dirname(realpath(__file__))))
from xbc3.fileio import FileIO


class CountCookie(object):
    """"""

    def __init__(self, *inputfiles):
        """"""
        super(CountCookie, self).__init__()
        self.files_name = []
        for fn in inputfiles:
            if isdir(fn):
                continue
            if 'sys_ss' in  basename(fn):
                self.files_name.append(fn)
        if not self.files_name:
            print('Error:can not find files!!!\n', file=sys.stderr)
            sys.exit()
        self.cookie_dict = {}

    def run(self):
        """"""
        for fn in self.files_name:
            self.count_cookie(fn)
        self.output()

    def count_cookie(self, filename):
        """"""
        file = FileIO(filename)
        for line in file:  
            try:
                cookie = line[44:76]
                if cookie in self.cookie_dict:
                    self.cookie_dict[cookie]+=1
                else:
                    self.cookie_dict[cookie]=1
            except Exception as e:
                pass
        sys.stdout.write('%s finished' % (filename))    

    def output(self):
        """"""
        fpath=os.path.split(self.files_name[0])[0]
        result_path=os.path.join(fpath,'result.csv')
        
        with FileIO(result_path,'w') as f:
            f.write('cookie,number\n')
            for k in sorted(self.cookie_dict, key=lambda x:self.cookie_dict[x],reverse=True):
                v = self.cookie_dict[k]
                f.write('%s, %d\n' % (k, v))


if __name__ == '__main__':
    '''driver'''
    inputfiles = []
    for line in sys.stdin:
        line = line.rstrip('\r\n')
        inputfiles.append(line)
    print(inputfiles)
    cc = CountCookie(*inputfiles)
    cc.run()
         


